import { sendMessage, onMessage } from 'webext-bridge';
import { Tabs } from 'webextension-polyfill';
import UserService from '~/api/user';
import {
  EXT_GET_IMAGE_CODE,
  EXT_CLICK_USER_LOGIN,
  EXT_SET_USER_TOKEN,
  EXT_GET_HOT_CITY,
  EXT_GET_HANG_YE,
  EXT_GET_USER_TOKEN,
  EXT_UPLOAD_RESUME,
} from '~/events';
import { storageToken } from '~/logic';

// only on dev mode
if (import.meta.hot) {
  // @ts-expect-error for background HMR
  import('/@vite/client');
  // load latest content script
  import('./contentScriptHMR');
}

browser.runtime.onInstalled.addListener((): void => {
  // eslint-disable-next-line no-console
  console.log('小点 Extension installed');
});

let previousTabId = 0;

// communication example: send previous tab title from background page
// see shim.d.ts for type declaration
browser.tabs.onActivated.addListener(async ({ tabId }: any) => {
  if (!previousTabId) {
    previousTabId = tabId;
    return;
  }

  let tab: Tabs.Tab;

  try {
    tab = await browser.tabs.get(previousTabId);
    previousTabId = tabId;
  } catch {
    return;
  }

  // eslint-disable-next-line no-console
  console.log('previous tab', tab);
  sendMessage(
    'tab-prev',
    { title: tab.title },
    { context: 'content-script', tabId }
  );
});

onMessage('get-current-tab', async () => {
  try {
    const tab = await browser.tabs.get(previousTabId);
    return {
      title: tab?.title,
    };
  } catch {
    return {
      title: undefined,
    };
  }
});

onMessage(EXT_GET_IMAGE_CODE, async () => {
  try {
    const resp = await UserService.getImageCode<any>();
    return resp;
  } catch (error: any) {
    return Promise.reject(error);
  }
});

onMessage(EXT_CLICK_USER_LOGIN, async args => {
  const resp = fetchLogin(args.data);
  return resp;
});

onMessage(EXT_SET_USER_TOKEN, ({ data }: any) => {
  storageToken.value = data.token;
});

onMessage(EXT_GET_USER_TOKEN, () => {
  return storageToken.value;
});

onMessage(EXT_GET_HOT_CITY, async () => {
  try {
    const resp = await UserService.getHotCityList();
    return resp;
  } catch (error: any) {
    return Promise.reject(error);
  }
});

onMessage(EXT_GET_HANG_YE, async () => {
  try {
    const resp = await UserService.getHotHangYeList();
    return resp;
  } catch (error: any) {
    return Promise.reject(error);
  }
});

onMessage(EXT_UPLOAD_RESUME, async ({ data }: any) => {
  try {
    const resp = await UserService.analResume(data);
    return resp;
  } catch (error: any) {
    return Promise.reject(error);
  }
});

async function fetchLogin(data: any) {
  try {
    const resp = UserService.userLogin(data);
    return resp;
  } catch (error) {
    return Promise.reject(error);
  }
}
